package com.lamda.zhekou.dao.impl;

import com.lamda.zhekou.dao.ExpireWarningRecordDao;
import com.lamda.zhekou.model.ExpireWarningRecord;
import com.lamda.zhekou.model.VPS;
import com.lamda.zhekou.vo.WarningResult;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;

import java.sql.Timestamp;

import static com.lamda.zhekou.model.ExpireWarningRecord.WarningType.OneDay;
import static com.lamda.zhekou.model.ExpireWarningRecord.WarningType.SevenDay;
import static com.lamda.zhekou.model.ExpireWarningRecord.WarningType.ThreeDay;

/**
 * Created by MJiao on 15/9/7.
 */
@Repository
public class ExpireWarningRecordDaoImpl extends GenericDaoImpl<ExpireWarningRecord> implements ExpireWarningRecordDao {

    @Override
    public synchronized ExpireWarningRecord judgeHasWarning(ExpireWarningRecord.WarningType warningType, VPS vps) {



        long gtDayTime = 86400000l * 3;
        long ltDayTime = 86400000l * 7;


        switch (warningType) {
            case SevenDay: {
                gtDayTime = 86400000l * 3;
                ltDayTime = 86400000l * 7;
            }
            break;
            case ThreeDay: {
                gtDayTime = 86400000l * 1;
                ltDayTime = 86400000l * 3;
            }
            break;
            case OneDay: {
                gtDayTime = 86400000l * 0;
                ltDayTime = 86400000l * 1;
            }
            break;
        }

        Timestamp gtTimestamp = new Timestamp(System.currentTimeMillis() + gtDayTime);
        Timestamp ltTimestamp = new Timestamp(System.currentTimeMillis() + ltDayTime);

        ExpireWarningRecord singleResult = null;

        String qlString = "select e from ExpireWarningRecord e where e.vps.id =:vpsId and e.warningTime > :gtTime and  e.warningTime < :ltTime and e.warningType =:warningType";

        try {
              singleResult = (ExpireWarningRecord) this.entityManager.createQuery(qlString)
                    .setParameter("vpsId", vps.getId())
                    .setParameter("ltTime", ltTimestamp)
                    .setParameter("gtTime", gtTimestamp)
                    .setParameter("warningType", warningType)
                    .getSingleResult();

        } catch (NoResultException e) {


        }
        return singleResult;
    }
}
